package com.monkey.luffer.springboot.demo.basis.xml;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicInteger;

public class XmlAnalysisMain {
    public static void main(String[] args) {
        //XML文件所在的文件夹路径
        String folderPath = "/Users/kaibing.deng/work/core-banking-gateway/src/main/resources/gateway-config";
        // 输出的Excel文件路径
        String excelFilePath = "/Users/kaibing.deng/work/core-banking-gateway/src/main/resources/gateway-config/output.xlsx";

        // 创建工作簿和工作表
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Data");
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("FieldName"); // 假设你要提取的字段名是"FieldName"

        AtomicInteger rowNum = new AtomicInteger(1);

        try {
            // 遍历文件夹获取所有XML文件
            Files.walk(Paths.get(folderPath))
                    .filter(Files::isRegularFile)
                    .filter(path -> path.toString().endsWith(".xml"))
                    .forEach(path -> {
                        try {
                            // 解析XML文件并提取字段
                            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                            //doc解析模式
                            Document doc = dBuilder.parse(path.toFile());
                            doc.getDocumentElement().normalize();

                            // 假设你要从根元素的某个子元素中提取字段，例如<element>FieldNameValue</element>
                            NodeList nList = doc.getElementsByTagName("ServiceConfig");
                            Row row = sheet.createRow(rowNum.getAndIncrement());
                            for (int temp = 0; temp < nList.getLength(); temp++) {
                                Element nNode = (Element)nList.item(temp);
                                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                                    Element eElement = (Element) nNode;
                                    //获取元素
                                    String id = eElement.getAttribute("id");
                                    String serviceCode = eElement.getAttribute("serviceCode");
                                    String serviceUrl=eElement.getAttribute("serviceUrl");

                                    // 将字段值写入Excel
                                    row.createCell(0).setCellValue(id);
                                    row.createCell(1).setCellValue(serviceCode);
                                    //如果是存在Url的 直接获取
                                    if(!StringUtils.isBlank(serviceUrl)){
                                        row.createCell(2).setCellValue(serviceUrl);
                                        break;
                                    }
                                    //获取该子节点的requestmapping
                                    NodeList requestMapping = eElement.getElementsByTagName("RequestMapping");
                                    //只取第一个
                                    NodeList fieldValues=null;
                                    if(requestMapping.getLength()>0) {
                                        Node requestMappingItem = requestMapping.item(0);
                                        Element element2 = (Element) requestMappingItem;
                                        NodeList objectMapping = element2.getElementsByTagName("ObjectMapping");
                                        Node objectItem = objectMapping.item(0);
                                        Element element3 = (Element) objectItem;
                                         fieldValues = element3.getElementsByTagName("FieldValue");
                                    }
                                    String content = "";
                                    for (int index = 0; index < fieldValues.getLength(); index++) {
                                        Element fieldValue = (Element) fieldValues.item(index);
                                        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                                            Element fieldValue1 = (Element) fieldValue;
                                            String target = fieldValue1.getAttribute("target");
                                            String value = fieldValue1.getAttribute("value");
                                            String text="<FieldValue target="+target+" value="+value+"/>";
                                            if(index!=fieldValues.getLength()-1){
                                                content = content +text+"\n" ;
                                            }else {
                                                content = content +text;
                                            }
                                        }
                                        }
                                    row.createCell(2).setCellValue(content);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });

            // 写入Excel文件
            try (FileOutputStream fileOut = new FileOutputStream(excelFilePath)) {
                workbook.write(fileOut);
            }
            System.out.println("Excel written successfully");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
